﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Demo.Controllers;
using Demo.Mapping;
using NHibernate.Burrow;
using NHibernate.Dialect;
using WB.Mvc.Forms;
using Configuration=NHibernate.Cfg.Configuration;

namespace Demo
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : HttpApplication
	{
		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new {controller = "Home", action = "Index", id = ""} // Parameter defaults
				);
		}

		protected void Application_Start()
		{
			RegisterRoutes(RouteTable.Routes);

			// Configure nhibernate using fluent nhibernate.
			var burrow = new BurrowFramework();
			Configuration config = burrow.BurrowEnvironment.GetNHConfig("Demo");

			MappingHelper.GetConnectionConfiguration(GetDbFilePath().Insert(0, "Data Source=")).ConfigureProperties(config);
			MappingHelper.GetMapper().Configure(config);

			burrow.BurrowEnvironment.RebuildSessionFactories();

			// Set up the model binder for PostModelForm
			ModelBinders.Binders.Add(typeof (PostModelForm), new ModelFormBinder());
		}

		protected void Application_PreRequestHandlerExecute(object sender, EventArgs args)
		{
			var dbPath = GetDbFilePath();
			if (!File.Exists(dbPath))
			{
				SQLiteConnection.CreateFile(dbPath);

				var burrow = new BurrowFramework();
				Configuration config = burrow.BurrowEnvironment.GetNHConfig("Demo");

				var session = burrow.GetSession();
				var scripts = config.GenerateSchemaCreationScript(new SQLiteDialect());
				foreach (string script in scripts)
				{
					IDbCommand cmd = session.Connection.CreateCommand();
					cmd.CommandText = script;
					cmd.ExecuteNonQuery();
				}
				session.Flush();
			}
		}

		protected virtual string GetDbFilePath()
		{
			return Server.MapPath(ConfigurationManager.AppSettings["sqlite_db_file"]);
		}
	}
}